package com.up.api.xianliu;

import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: liuchengjun
 * @title: MyTest
 * @projectName: 海联技术中台V2.0
 * @depart 软件事业部
 * @description:
 * @date: 2023/12/19/019 14:31 (星期二)
 * @since V2.0
 */
@Component
public class MyTest {
    private final int windowSize; // 滑动窗口的大小
    private final int maxRequests; // 窗口内允许的最大请求数
    private final LinkedList<Long> timestamps; // 用于存储每个请求的时间戳

    public MyTest() {
        this.windowSize = 1000;
        this.maxRequests = 50;
        this.timestamps = new LinkedList<>();
    }

    public synchronized boolean allowRequest() {
        long currentTime = System.currentTimeMillis();
        // 移除过期的时间戳
        while (!timestamps.isEmpty() && timestamps.getFirst() <= currentTime - windowSize) {
            timestamps.removeFirst();
        }
        // 检查当前窗口内的请求数是否超过阈值
        if (timestamps.size() < maxRequests) {
            // 允许请求，添加当前请求的时间戳
            timestamps.addLast(currentTime);
            return true;
        } else {
            // 请求超过阈值，拒绝请求
            return false;
        }
    }
    public static void main(String[] args) throws InterruptedException {
        int windowSize = 1000; // 滑动窗口大小，单位：毫秒
        int maxRequests = 50; // 窗口内允许的最大请求数

        MyTest limiter = new MyTest();
        // 模拟请求
        int success = 0;
        int now1 = (int) System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            if (limiter.allowRequest()) {
                success++;
                System.out.println("允许请求 " + i);
            } else {
                System.out.println("拒绝请求 " + i);
            }
            Thread.sleep(5);
        }
        int now2 = (int) System.currentTimeMillis()-now1;
        System.out.println("在"+now2+"ms内的通过请求数为:"+success);

        Thread.sleep(1000);
        success = 0;
        int now3 = (int) System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            if (limiter.allowRequest()) {
                success++;
                System.out.println("允许请求 " + i);
            } else {
                System.out.println("拒绝请求 " + i);
            }
            Thread.sleep(5);
        }
        int now4 = (int) System.currentTimeMillis()-now3;
        System.out.println("在"+now4+"ms内的通过请求数为:"+success);
    }


}
